<template>
  <view class="content">
    <roc-navbar title="修改密码"></roc-navbar>
    <u-form ref="formRef" :model="form" :rules="rules" labelPosition="top" label-width="100%">
      <u-form-item label="旧密码" prop="oldPassword" required>
        <u-input v-model="form.oldPassword" placeholder="请输入旧密码" type="password"></u-input>
      </u-form-item>
      <u-form-item label="新密码" prop="password" required>
        <u-input v-model="form.password" placeholder="请输入新密码" type="password"></u-input>
      </u-form-item>
      <u-form-item label="确认密码" prop="passwordTwo" required>
        <u-input v-model="form.passwordTwo" placeholder="请确认密码" type="password"></u-input>
      </u-form-item>
    </u-form>
    <u-button type="primary" @click="submit">修改</u-button>
  </view>
</template>

<script>
import { updateUserPwd } from '@/mock/user.js'
import { removeLoginState } from '@/utils/roc.js'
export default {
  data() {
    return {
      // 表单数据
      form: {
        oldPassword: '',
        password: '',
        passwordTwo: '',
      },
      rules: {
        oldPassword: [
          {
            required: true,
            message: '旧密码不能为空',
            trigger: ['change', 'blur'],
          },
        ],
        password: [
          {
            required: true,
            message: '新密码不能为空',
            trigger: ['change', 'blur'],
          },
        ],
        passwordTwo: [
          {
            required: true,
            message: '确认密码不能为空',
            trigger: ['change', 'blur'],
          },
          {
            validator: this.validatePasswordTwo,
            trigger: ['change', 'blur'],
          },
        ],
      },
    }
  },
  onReady() {
    this.$refs['formRef'].setRules(this.rules)
  },
  methods: {
    /**
     * 提交表单
     */
    submit() {
      this.$refs['formRef']
        .validate()
        .then(res => {
          updateUserPwd({
            oldPassword: this.form.oldPassword,
            newPassword: this.form.password,
          }).then(() => {
            // 修改成功后重新登录
            uni.$u.toast('修改成功，请重新登录')
            this.$store.dispatch('user/logout').then(() => {
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/login/login',
                })
              }, 1000)
            })
          })
        })
        .catch(err => {
          console.log('表单错误信息：', err)
        })
    },
    /**
     * 自定义验证二次密码
     * @param rule
     * @param value
     * @param callback
     */
    validatePasswordTwo(rule, value, callback) {
      if (value !== this.form.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.content {
  padding: 30px 20px 0;
  .u-button {
    font-size: 16px;
    margin-top: 30px;
  }
}
</style>
